package com.liuqi.voicenotes.ui

import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.liuqi.voicenotes.data.Task
import com.liuqi.voicenotes.data.TaskRepository
import com.liuqi.voicenotes.domain.Parser
import com.liuqi.voicenotes.reminder.ReminderScheduler
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch

class TasksViewModel(
    private val repository: TaskRepository,
    private val appContext: Context
) : ViewModel() {
    val tasks: Flow<List<Task>> = repository.tasks
    fun addFromSpeech(text: String) {
        viewModelScope.launch {
            val parsed = Parser.parseSpeechToTask(appContext, text, 0)
            if (parsed != null) {
                val id = repository.add(parsed)
                val withId = parsed.copy(id = id)
                withId.dueAtMillis?.let { ReminderScheduler.scheduleForTask(appContext, id, withId.title, it) }
            }
        }
    }
    fun update(task: Task) {
        viewModelScope.launch {
            repository.update(task)
            if (task.dueAtMillis != null && !task.completed) {
                ReminderScheduler.scheduleForTask(appContext, task.id, task.title, task.dueAtMillis!!)
            } else {
                ReminderScheduler.cancelForTask(appContext, task.id)
            }
        }
    }

    fun delete(task: Task) {
        viewModelScope.launch {
            ReminderScheduler.cancelForTask(appContext, task.id)
            repository.delete(task)
        }
    }

    fun toggleCompleted(task: Task) {
        viewModelScope.launch {
            val newCompleted = !task.completed
            repository.setCompleted(task.id, newCompleted)
            if (newCompleted) {
                ReminderScheduler.cancelForTask(appContext, task.id)
            } else if (task.dueAtMillis != null) {
                ReminderScheduler.scheduleForTask(appContext, task.id, task.title, task.dueAtMillis!!)
            }
        }
    }

    // 直接接收已解析的 Task，避免重复解析与重复请求 LLM
    fun addParsedTask(task: Task) {
        viewModelScope.launch {
            val id = repository.add(task)
            val withId = task.copy(id = id)
            withId.dueAtMillis?.let { ReminderScheduler.scheduleForTask(appContext, id, withId.title, it) }
        }
    }
}